<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown, Box } from '@element-plus/icons-vue'
// @ts-ignore
import { ReadClients } from '@/Urls/AxiosHelper'

const router = useRouter()
const route = useRoute()
const routeBomNumber = computed(() => (route.query.bomNumber as string) || '')
const readClient = ReadClients[3]

const loading = ref(false)
const data = ref<any>({
  bomNumber: routeBomNumber.value,
  creator: '系统管理员',
  createTime: '2024-01-15 10:30:00',
  updater: '系统管理员',
  updateTime: '2024-01-15 10:30:00',
})
const activeTab = ref('info')

// 物料配件数据
const productMaterialList = ref<any[]>([])
const materialStructureList = ref<any[]>([])
const processSteps = ref<any[]>([])
const activeStepIndex = ref(0)
const stepMaterials = ref<any[]>([])

// 加载状态
const listLoading = ref(false)
const processLoading = ref(false)

function handleEdit(){ 
  router.push({ name: 'BomEdit', query: { bomNumber: routeBomNumber.value, origin: 'detail' } })
}

function handleDelete(){
  // 纯前端删除占位：后续接入接口后仅用 bomNumber 调用服务端
  router.push({ name: 'BomInfo' })
}

function handleCopy(){}
function handleExport(){}

// 按 BomNumber 查询基础信息并反填
async function fetchBaseInfoByBomNumber(bomNumber:string){
  if(!bomNumber) return
  try{
    loading.value = true
    const res = await readClient.get('/productread/api/Bom/GetBomInfoByBomNumber', { params:{ BomNumber: bomNumber } })
    const payload = res?.data
    const item = payload?.data || payload || {}
    data.value = {
      ...data.value,
      bomNumber: item.bomNumber || bomNumber,
      version: item.bomVersion || item.version || data.value?.version,
      productName: item.productName || data.value?.productName,
      productNumber: item.productNumber || data.value?.productNumber,
      specificationModel: item.specificationModel || data.value?.specificationModel,
      unit: item.unit || data.value?.unit,
      isDefaultBom: item.isDefaultBom ?? data.value?.isDefaultBom,
      dailyOutput: item.dailyOutput ?? data.value?.dailyOutput,
      remarks: item.remarks || data.value?.remarks,
      processRouteNumber: item.processRouteNumber || data.value?.processRouteNumber,
    }
    
    // 获取物料配件数据
    await fetchProductMaterials(bomNumber)
    
    // 获取BOM结构数据
    await fetchMaterialStructure(bomNumber)
    
    // 获取工艺路线数据
    if (data.value.processRouteNumber) {
      await fetchProcessRoute(data.value.processRouteNumber)
    }
  }catch(error){
    console.error('获取BOM详情失败:', error)
    ElMessage.error('获取BOM详情失败')
  }finally{
    loading.value = false
  }
}

// 获取物料配件数据
async function fetchProductMaterials(bomNumber: string) {
  try {
    listLoading.value = true
    let res
    try {
      res = await readClient.get('/productread/api/Bom/GetProductMaterialByBomNumber', { params: { BomNumber: bomNumber } })
    } catch (e) {
      // 一些环境大小写不同，做一次兼容
      res = await readClient.get('/productread/api/BOM/GetProductMaterialByBomNumber', { params: { BomNumber: bomNumber } })
    }
    
    const payload = res?.data
    const items = payload?.data || payload?.items || payload?.rows || payload?.list || payload || []
    productMaterialList.value = items.map((item: any) => ({
      id: item.id,
      materialNumber: item.materialNumber,
      materialName: item.materialName,
      specificationModel: item.specificationModel,
      unit: item.unit,
      materialRatio: item.materialRatio || ''
    }))
  } catch (error) {
    console.error('获取物料配件失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 获取BOM结构数据
async function fetchMaterialStructure(bomNumber: string) {
  try {
    const res = await readClient.get('/productread/api/Bom/GetMaterialStructureByBomNumber', { 
      params: { BomNumber: bomNumber } 
    })
    
    const payload = res?.data
    const items = payload?.data || payload?.items || payload?.rows || payload?.list || payload || []
    materialStructureList.value = items.map((item: any) => ({
      id: item.id,
      materialStructureNumber: item.materialStructureNumber,
      parentProductNumber: item.parentProductNumber,
      productMaterialName: item.productMaterialName,
      childNumber: item.childNumber,
      bomNumber: item.bomNumber
    }))
  } catch (error) {
    console.error('获取BOM结构失败:', error)
  }
}

// 获取工艺路线数据
async function fetchProcessRoute(processRouteNumber: string) {
  try {
    processLoading.value = true
    const processRes = await readClient.get('/productread/api/Process/GetProcessById', { 
      params: { processRouteNumber: processRouteNumber } 
    })
    
    const processData = processRes?.data
    const processItems = processData?.data || processData?.items || processData?.rows || processData?.list || processData || []
    
    // 按 serialNumber 排序
    const sortedProcessItems = processItems.sort((a: any, b: any) => {
      const serialA = a.serialNumber || 0
      const serialB = b.serialNumber || 0
      return serialA - serialB
    })
    
    processSteps.value = sortedProcessItems.map((process: any) => ({
      id: process.id,
      processSerialNumber: process.serialNumber,
      processName: process.processName || process.name,
      materials: [] // 初始为空，点击时动态加载
    }))
    
    if (processSteps.value.length > 0) {
      activeStepIndex.value = 0
      await handleStepClick(0)
    }
  } catch (error) {
    console.error('获取工艺路线失败:', error)
  } finally {
    processLoading.value = false
  }
}

// 点击工序步骤
async function handleStepClick(index: number) {
  activeStepIndex.value = index
  const process = processSteps.value[index]
  
  // 如果该工序还没有物料数据，则动态加载
  if (process.materials.length === 0 && data.value.productNumber && process.processSerialNumber) {
    try {
      const materialRes = await readClient.get('/productread/api/Bom/GetProductMaterialByProductNumberAndSerial', {
        params: {
          ProductNumber: data.value.productNumber,
          SerialNumber: process.processSerialNumber
        }
      })
      
      const materialData = materialRes?.data
      const materials = materialData?.data || materialData?.items || materialData?.rows || materialData?.list || materialData || []
      
      process.materials = materials.map((material: any) => ({
        id: material.id,
        materialNumber: material.materialNumber,
        materialName: material.materialName,
        specificationModel: material.specificationModel,
        unit: material.unit,
        usageQuantity: material.usageQuantity || 1,
        materialRatio: material.materialRatio || '',
        processSerialNumber: process.processSerialNumber
      }))
      
      stepMaterials.value = process.materials
    } catch (error) {
      console.error(`获取工序${process.processSerialNumber}物料失败:`, error)
    }
  } else {
    stepMaterials.value = process.materials
  }
}

// 进入或路由变化时拉取基础信息
watch(routeBomNumber, (bn)=>{ if(bn) fetchBaseInfoByBomNumber(bn) }, { immediate: true })
</script>

<template>
  <div class="detail-wrap" v-loading="loading">
    <!-- 顶部信息区域 -->
    <el-card class="header-card">
      <div class="header-section">
        <div class="header-info">
          <div class="title-row">
            <h1 class="main-title">{{ data?.bomNumber || 'BOM详情' }}</h1>
            <span class="version">{{ data?.version || '' }}</span>
            <el-tag v-if="data?.isDefaultBom" type="warning" size="small">默认</el-tag>
          </div>
          <div class="meta-info">
            <div class="meta-row">
              <span class="meta-item">创建人: {{ data?.creator || '李小海' }}</span>
              <span class="meta-item">创建时间: {{ data?.createTime || '2025-09-22 11:26:17' }}</span>
            </div>
            <div class="meta-row">
              <span class="meta-item">更新人: {{ data?.updater || '李小海' }}</span>
              <span class="meta-item">更新时间: {{ data?.updateTime || '2025-09-22 11:26:17' }}</span>
            </div>
          </div>
        </div>
        <div class="action-buttons">
          <el-button @click="handleEdit">编辑</el-button>
          <el-button @click="handleDelete">删除</el-button>
          <el-button @click="handleCopy">复制</el-button>
          <el-button @click="handleExport">导出</el-button>
        </div>
      </div>
    </el-card>

    <!-- 标签页内容区域 -->
    <el-card class="content-card">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="基础信息" name="info">
          <div class="info-grid">
            <div class="info-item">
              <label>BOM编号</label>
              <span>{{ data?.bomNumber || 'BOM0002145' }}</span>
            </div>
            <div class="info-item">
              <label>BOM版本</label>
              <span>{{ data?.version || '1.0' }}</span>
            </div>
            <div class="info-item">
              <label>默认BOM</label>
              <span>{{ data?.isDefaultBom ? '是' : '否' }}</span>
            </div>
            <div class="info-item">
              <label>成品编号</label>
              <span>{{ data?.productNumber || 'CP021554' }}</span>
            </div>
            <div class="info-item">
              <label>单位</label>
              <span>{{ data?.unit || '瓶' }}</span>
            </div>
            <div class="info-item">
              <label>当前库存</label>
              <span class="inventory">
                {{ data?.currentInventory || '500' }}
                <el-icon class="arrow-down"><ArrowDown /></el-icon>
              </span>
            </div>
            <div class="info-item">
              <label>成品名称</label>
              <span>{{ data?.productName || '新产品一' }}</span>
            </div>
            <div class="info-item">
              <label>规格型号</label>
              <span>{{ data?.specificationModel || '红色' }}</span>
            </div>
            <div class="info-item">
              <label>日产量</label>
              <span>{{ data?.dailyOutput || '30' }}</span>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="物料配件" name="materials">
          <div v-if="productMaterialList.length === 0" class="empty-state">
            <el-icon class="empty-icon"><Box /></el-icon>
            <div class="empty-text">暂无物料配件数据</div>
          </div>
          <el-table v-else :data="productMaterialList" v-loading="listLoading" style="width: 100%">
            <el-table-column prop="materialNumber" label="物料编号" width="150" />
            <el-table-column prop="materialName" label="物料名称" width="200" />
            <el-table-column prop="specificationModel" label="规格型号" width="150" />
            <el-table-column prop="unit" label="单位" width="100" />
            <el-table-column prop="materialRatio" label="物料比例" width="120" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="BOM结构" name="structure">
          <div v-if="materialStructureList.length === 0" class="empty-state">
            <el-icon class="empty-icon"><Box /></el-icon>
            <div class="empty-text">暂无BOM结构数据</div>
          </div>
          <el-table v-else :data="materialStructureList" style="width: 100%">
            <el-table-column prop="materialStructureNumber" label="结构编号" width="200" />
            <el-table-column prop="productMaterialName" label="产品物料名称" width="300" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="工艺路线" name="process">
          <div v-if="processSteps.length === 0" class="empty-state">
            <el-icon class="empty-icon"><Box /></el-icon>
            <div class="empty-text">暂无工艺路线数据</div>
          </div>
          <div v-else>
            <el-steps :active="activeStepIndex" finish-status="success" style="margin-bottom: 20px;">
              <el-step
                v-for="(process, index) in processSteps"
                :key="index"
                :title="`工序${index + 1}`"
                :description="process.processName"
                @click="handleStepClick(index)"
                style="cursor: pointer;"
              />
            </el-steps>
            
            <div v-if="activeStepIndex >= 0" class="process-materials">
              <div class="process-step">
                <h4>工序{{ activeStepIndex + 1 }}：{{ processSteps[activeStepIndex].processName }}</h4>
                
                <div v-if="stepMaterials.length === 0" class="empty-state">
                  <el-icon class="empty-icon"><Box /></el-icon>
                  <div class="empty-text">该工序暂无物料数据</div>
                </div>
                <el-table v-else :data="stepMaterials" style="width: 100%; margin-top: 10px">
                  <el-table-column prop="materialNumber" label="物料编号" width="150" />
                  <el-table-column prop="materialName" label="物料名称" width="200" />
                  <el-table-column prop="specificationModel" label="规格型号" width="150" />
                  <el-table-column prop="unit" label="单位" width="100" />
                  <el-table-column prop="usageQuantity" label="用量" width="120" />
                  <el-table-column prop="materialRatio" label="物料比例" width="120" />
                </el-table>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="变更记录" name="changes">
          <div class="empty-state">
            <el-icon class="empty-icon"><Box /></el-icon>
            <div class="empty-text">暂无数据</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 返回按钮 -->
    <el-card class="action-card">
      <div class="action-buttons">
        <el-button size="large" type="primary" @click="router.push({ name: 'BomInfo' })">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.detail-wrap {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 顶部信息卡片 */
.header-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.header-card :deep(.el-card__body) {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-info {
  flex: 1;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.version {
  font-size: 16px;
  color: #606266;
  background: #f5f7fa;
  padding: 4px 12px;
  border-radius: 4px;
}

.meta-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-row {
  display: flex;
  gap: 32px;
  color: #606266;
  font-size: 14px;
}

.meta-item {
  background: #f5f7fa;
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.action-buttons .el-button {
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 4px;
}

/* 内容卡片 */
.content-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.content-card :deep(.el-card__body) {
  padding: 0;
}

.detail-tabs :deep(.el-tabs__header) {
  margin: 0;
  background: #f5f7fa;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}

.detail-tabs :deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
  color: #606266;
  padding: 16px 24px;
  border: none;
}

.detail-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  background: white;
  border-radius: 6px 6px 0 0;
}

.detail-tabs :deep(.el-tabs__item:hover) {
  color: #409eff;
}

.detail-tabs :deep(.el-tabs__content) {
  padding: 24px;
}

/* 基础信息网格 */
.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  max-width: 800px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.info-item span {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.inventory {
  display: flex;
  align-items: center;
  gap: 8px;
}

.arrow-down {
  color: #909399;
  cursor: pointer;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-text {
  font-size: 16px;
  color: #909399;
}

/* 返回按钮卡片 */
.action-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.action-card :deep(.el-card__body) {
  padding: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.action-buttons .el-button {
  font-weight: 500;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
}

/* 工艺路线样式 */
.process-materials {
  margin-top: 20px;
}

.process-step {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.process-step h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    gap: 20px;
    padding: 16px;
  }
  
  .meta-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .detail-tabs :deep(.el-tabs__content) {
    padding: 16px;
  }
}
</style>
